/**
 * 评论状态管理 Store
 */
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { createCommentApi } from '@/apis/methods/comment.api'
import { mockInstance } from '@/apis/instances'
import type { Comment, CreateCommentData, CommentListParams } from '@/apis/methods/comment.api'
import {
  handlePaginatedApiResponse,
  handleApiResponse,
  isApiSuccess,
  getApiErrorMessage,
} from '@/utils/api-response'

// 创建评论 API 实例
const commentApi = createCommentApi(mockInstance)

export const useCommentStore = defineStore('comment', () => {
  // 状态
  const comments = ref<Comment[]>([])
  const repliesData = ref<Record<string, Comment[]>>({})
  const loading = ref(false)
  const submitting = ref(false)
  const loadingMore = ref(false)
  const showReplies = ref<Record<string, boolean>>({})
  const replyPages = ref<Record<string, number>>({})
  const hasMoreReplies = ref<Record<string, boolean>>({})

  // 分页状态
  const currentPage = ref(1)
  const pageSize = ref(20)
  const totalComments = ref(0)
  const hasMore = ref(false)

  // 计算属性
  const topLevelComments = computed(() => comments.value.filter((comment) => !comment.parentId))

  // Actions
  /**
   * 获取评论列表
   */
  const fetchComments = async (params: CommentListParams, append = false) => {
    if (params.page === 1) {
      loading.value = true
    } else {
      loadingMore.value = true
    }

    try {
      const response = await commentApi.getComments(params)
      const apiResponse = handlePaginatedApiResponse(response)

      if (isApiSuccess(apiResponse)) {
        if (append) {
          comments.value = [...comments.value, ...apiResponse.data]
        } else {
          comments.value = apiResponse.data
        }

        currentPage.value = Number(apiResponse.pagination.page)
        totalComments.value = apiResponse.pagination.total
        hasMore.value = apiResponse.pagination.hasNext
      } else {
        console.error('获取评论失败:', getApiErrorMessage(apiResponse))
      }
    } catch (error) {
      console.error('获取评论失败:', error)
      throw error
    } finally {
      loading.value = false
      loadingMore.value = false
    }
  }

  /**
   * 加载更多评论
   */
  const loadMoreComments = async (articleId: string) => {
    if (!hasMore.value || loadingMore.value) return

    await fetchComments(
      {
        articleId,
        page: currentPage.value + 1,
        limit: pageSize.value,
        parentId: null,
      },
      true,
    )
  }

  /**
   * 创建评论
   */
  const createComment = async (data: CreateCommentData) => {
    submitting.value = true
    try {
      const response = await commentApi.createComment(data)
      const apiResponse = handleApiResponse(response)

      if (isApiSuccess(apiResponse)) {
        comments.value.unshift(apiResponse.data)
        totalComments.value++
        return apiResponse.data
      } else {
        console.error('创建评论失败:', getApiErrorMessage(apiResponse))
        throw new Error(getApiErrorMessage(apiResponse))
      }
    } catch (error) {
      console.error('创建评论失败:', error)
      throw error
    } finally {
      submitting.value = false
    }
  }

  /**
   * 创建回复
   */
  const createReply = async (parentId: string, data: Omit<CreateCommentData, 'parentId'>) => {
    submitting.value = true
    try {
      const response = await commentApi.createComment({
        ...data,
        parentId,
      })
      const apiResponse = handleApiResponse(response)

      if (isApiSuccess(apiResponse)) {
        if (!repliesData.value[parentId]) {
          repliesData.value[parentId] = []
        }
        repliesData.value[parentId].push(apiResponse.data)

        // 更新评论的回复数量
        const comment = comments.value.find((c) => c.id === parentId)
        if (comment && comment.replyCount !== undefined) {
          comment.replyCount++
        }

        return apiResponse.data
      } else {
        console.error('创建回复失败:', getApiErrorMessage(apiResponse))
        throw new Error(getApiErrorMessage(apiResponse))
      }
    } catch (error) {
      console.error('创建回复失败:', error)
      throw error
    } finally {
      submitting.value = false
    }
  }

  /**
   * 点赞/取消点赞
   */
  const toggleLike = async (commentId: string, userId: string) => {
    try {
      const response = await commentApi.toggleLike(commentId, userId)
      const apiResponse = handleApiResponse(response)

      if (isApiSuccess(apiResponse)) {
        // 更新主评论
        const comment = comments.value.find((c) => c.id === commentId)
        if (comment) {
          comment.likes = apiResponse.data.likes
          comment.isLiked = apiResponse.data.isLiked
          return
        }

        // 更新回复评论
        for (const replies of Object.values(repliesData.value)) {
          const reply = replies.find((r) => r.id === commentId)
          if (reply) {
            reply.likes = apiResponse.data.likes
            reply.isLiked = apiResponse.data.isLiked
            break
          }
        }
      } else {
        console.error('点赞失败:', getApiErrorMessage(apiResponse))
        throw new Error(getApiErrorMessage(apiResponse))
      }
    } catch (error) {
      console.error('点赞失败:', error)
      throw error
    }
  }

  /**
   * 切换回复显示
   */
  const toggleRepliesDisplay = async (commentId: string) => {
    showReplies.value[commentId] = !showReplies.value[commentId]

    // 如果是展开且还没加载过回复，则加载回复
    if (showReplies.value[commentId] && !repliesData.value[commentId]) {
      await loadReplies(commentId)
    }
  }

  /**
   * 加载回复
   */
  const loadReplies = async (parentId: string, page = 1) => {
    try {
      const response = await commentApi.getReplies(parentId, { page, limit: 5 })
      const apiResponse = handlePaginatedApiResponse(response)

      if (isApiSuccess(apiResponse)) {
        if (!repliesData.value[parentId]) {
          repliesData.value[parentId] = []
        }

        if (page === 1) {
          repliesData.value[parentId] = apiResponse.data
        } else {
          repliesData.value[parentId] = [...repliesData.value[parentId], ...apiResponse.data]
        }

        replyPages.value[parentId] = Number(apiResponse.pagination.page)
        hasMoreReplies.value[parentId] = apiResponse.pagination.hasNext
      } else {
        console.error('获取回复失败:', getApiErrorMessage(apiResponse))
      }
    } catch (error) {
      console.error('加载回复失败:', error)
      throw error
    }
  }

  /**
   * 加载更多回复
   */
  const loadMoreReplies = async (parentId: string) => {
    const nextPage = (replyPages.value[parentId] || 1) + 1
    await loadReplies(parentId, nextPage)
  }

  /**
   * 重置状态
   */
  const resetState = () => {
    comments.value = []
    repliesData.value = {}
    showReplies.value = {}
    replyPages.value = {}
    hasMoreReplies.value = {}
    currentPage.value = 1
    totalComments.value = 0
    hasMore.value = false
    loading.value = false
    submitting.value = false
    loadingMore.value = false
  }

  return {
    // 状态
    comments,
    repliesData,
    loading,
    submitting,
    loadingMore,
    showReplies,
    replyPages,
    hasMoreReplies,
    currentPage,
    pageSize,
    totalComments,
    hasMore,

    // 计算属性
    topLevelComments,

    // Actions
    fetchComments,
    loadMoreComments,
    createComment,
    createReply,
    toggleLike,
    toggleRepliesDisplay,
    loadReplies,
    loadMoreReplies,
    resetState,
  }
})
